﻿using System;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using Meqs.Entity;
using Meqs.Logic.Interface;
using System.Collections;
using System.Collections.Generic;


/// <summary>
/// Common 的摘要说明

/// </summary>
public class Common
{
    public Common()
    {

    }

    /// <summary>
    /// 测试用获取学校编号

    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string GetConstSchoolMark()
    {
        Perm perm = HttpContext.Current.Session["UserInfo"] as Perm;
        return perm.SchoolMark;
    }

    /// <summary>
    /// 获取权限对象
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static Perm GetUserInfo()
    {
        Perm perm = HttpContext.Current.Session["UserInfo"] as Perm;
        return perm;
    }

    /// <summary>
    /// 获取初始密码
    /// </summary>
    /// <returns></returns>
    public static string GetStartPwd()
    {
        return "123456";
    }

    /// <summary>
    /// 转换学校性质
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string ConvertSchoolOptNum(int num)
    {
        if (num <= 0 || num > 6) return "";
        string[] OptStrArr = { "小学", "初中", "高中", "小学、初中", "初中、高中", "小学、初中、高中" };

        return OptStrArr[num - 1];
    }

    /// <summary>
    /// 转换年级
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string ConvertGradeNum(int num)
    {
        if (num <= 0 || num > 12) return "";
        string[] GradeStrArr = { "一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "初一", "初二", "初三", "高一", "高二", "高三" };

        return GradeStrArr[num - 1];
    }

    /// <summary>
    /// 获取学分评估状态
    /// </summary>
    /// <param name="num">-1-未录入，0-未录入，1-已确定</param>
    /// <returns></returns>
    public static string ConvertStatus(int num)
    {
        if (num < -1 || num > 1) return "";
        string[] statusArr = { "未录入", "已录入", "已确定" };

        return statusArr[num+1];
    }

    /// <summary>
    /// 根据学校性质获取年级列表
    /// </summary>
    /// <param name="OptNum"></param>
    /// <returns></returns>
    public static List<int> GetGradeList(int OptNum)
    {
        List<int> resultList = new List<int>();
        switch (OptNum)
        {
            case 1:
                resultList.Add(1);
                resultList.Add(2);
                resultList.Add(3);
                resultList.Add(4);
                resultList.Add(5);
                resultList.Add(6);
                break;
            case 2:
                resultList.Add(7);
                resultList.Add(8);
                resultList.Add(9);
                break;
            case 3:
                resultList.Add(10);
                resultList.Add(11);
                resultList.Add(12);
                break;
            case 4:
                resultList.Add(1);
                resultList.Add(2);
                resultList.Add(3);
                resultList.Add(4);
                resultList.Add(5);
                resultList.Add(6);
                resultList.Add(7);
                resultList.Add(8);
                resultList.Add(9);
                break;
            case 5:
                resultList.Add(7);
                resultList.Add(8);
                resultList.Add(9);
                resultList.Add(10);
                resultList.Add(11);
                resultList.Add(12);
                break;
            case 6:
                resultList.Add(1);
                resultList.Add(2);
                resultList.Add(3);
                resultList.Add(4);
                resultList.Add(5);
                resultList.Add(6);
                resultList.Add(7);
                resultList.Add(8);
                resultList.Add(9);
                resultList.Add(10);
                resultList.Add(11);
                resultList.Add(12);
                break;
            default:
                break;
        }
        return resultList;
    }

    //MD5加密
    //参数:待加密字符串
    //返回:加密后的字符串

    public static string UserMd5(string str)
    {
        string cl = str;
        string pwd = "";
        MD5 md5 = MD5.Create();//实例化一个md5对像
        // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
        byte[] s = md5.ComputeHash(Encoding.Default.GetBytes(cl));
        // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得

        for (int i = 0; i < s.Length; i++)
        {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 

            pwd = pwd + s[i].ToString("X2");

        }
        return pwd;
    }

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="sn"></param>
    /// <param name="pc"></param>
    /// <returns></returns>
    public static string Encrypt(string sn, string pc)
    {
        string s = "";
        string p = "";
        if (!string.IsNullOrEmpty(sn))
        {
            s = sn.Trim();
        }
        if (!string.IsNullOrEmpty(pc))
        {
            p = pc.Trim();
        }
        return UserMd5(s + p);
    }

    /// <summary>
    /// 取得网卡mac地址
    /// </summary>
    /// <returns></returns>
    public static String GetMacAddress()
    {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        string MacAddress = "";

        foreach (ManagementObject mo in moc)
        {
            if ((bool)mo["IPEnabled"] == true)
            {
                MacAddress += mo["MacAddress"].ToString();
            }
            mo.Dispose();
        }
        return MacAddress;
    }

    /// <summary>
    /// 填充GridView
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="fillTableRow"></param>
    public static void FillGridView(GridView gv, int fillTableRow)
    {
        if (gv.Rows.Count != gv.PageSize)
        {
            if (gv.Controls.Count == 0)
            {
                gv.Controls.Add(new Table());

            }

            Control table = gv.Controls[0];

            if (table != null)
            {
                if (gv.Rows.Count == 0)
                {
                    GridViewRow head = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);
                    //head.CssClass = "staffTitle";
                    for (int i = 0; i < gv.Columns.Count; i++)
                    {
                        TableCell cell = new TableCell();
                        cell.Text = gv.Columns[i].HeaderText;
                        cell.Style["width"] = gv.Columns[i].HeaderStyle.Width.ToString();
                        head.Controls.Add(cell);
                    }
                    table.Controls.Add(head);
                }
                for (int i = 0; i < fillTableRow - gv.Rows.Count; i++)
                {
                    int rowIndex = gv.Rows.Count + i + 1;
                    GridViewRow row = new GridViewRow(rowIndex, -1, DataControlRowType.Separator, DataControlRowState.Normal);
                    //row.CssClass = (rowIndex % 2 == 0) ? "alternate" : "item";
                    for (int j = 0; j < gv.Columns.Count; j++)
                    {
                        TableCell cell = new TableCell();
                        cell.Text = "&nbsp;";
                        row.Controls.Add(cell);
                    }
                    table.Controls.Add(row);
                }
            }
        }
    }

    /// <summary>
    /// 截断字符串

    /// </summary>
    /// <param name="resourceStr">源字符串</param>
    /// <param name="cutLength">截断长度</param>
    /// <param name="cutStr">替换结尾</param>
    /// <returns></returns>
    public static string CutOffString(string resourceStr, int cutLength, string cutStr)
    {
        //resourceStr = HttpContext.Current.Server.HtmlDecode(resourceStr);
        if (resourceStr.Length <= cutLength) return resourceStr;
        return resourceStr.Substring(0, cutLength) + cutStr;
    }

    /// <summary>
    /// 获取权限下拉列表
    /// </summary>
    /// <returns></returns>
    public static string GetPremOption(int premType)
    {
        string result = "";
        ISystemInfoLogic systemInfoLogic = Container<ISystemInfoLogic>.Instance;
        IPremInfoLogic premInfoLogic = Container<IPremInfoLogic>.Instance;

        List<SystemInfo> systemInfoList = (List<SystemInfo>)systemInfoLogic.FindAll();
        if (systemInfoList == null) return "";
        foreach (SystemInfo systemInfo in systemInfoList)
        {
            string group = "<optgroup label=\"" + systemInfo.SystemName + "\">";

            Hashtable ht = new Hashtable();
            ht.Add("SystemNo", systemInfo.SystemNo);
            ht.Add("PremType", premType);
            List<PremInfo> premInfoList = (List<PremInfo>)premInfoLogic.FindAll(ht);
            if (premInfoList == null) return "";
            //如果系统下没有权限值，则不添加进列表中
            if (premInfoList.Count == 0) continue;

            foreach (PremInfo premInfo in premInfoList)
            {
                string option = "<option value=\"" + premInfo.PremNo + "\">" + premInfo.PremName + "</option>";
                group += option;
            }

            group += "</optgroup>";

            result += group;
        }

        return result;
    }

    /// <summary>
    /// 获取班级下拉列表
    /// </summary>
    /// <returns></returns>
    public static string GetClassOption()
    {
        string result = "";
        ISchoolInfoLogic schoolInfoLogic = Container<ISchoolInfoLogic>.Instance;
        IClsInfoLogic clsInfoLogic = Container<IClsInfoLogic>.Instance;

        Hashtable htSchool = new Hashtable();
        htSchool.Add("SchoolMark", Common.GetConstSchoolMark());
        List<SchoolInfo> list = (List<SchoolInfo>)schoolInfoLogic.FindAll(htSchool);
        if (list == null || list.Count == 0) return "";

        List<int> gradeList = Common.GetGradeList(list[0].SchoolOpt);
        foreach (int grade in gradeList)
        {
            string group = "<optgroup label=\"" + Common.ConvertGradeNum(grade) + "\">";

            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", Common.GetConstSchoolMark());
            ht.Add("Grade", grade);
            ht.Add("IsEffect", 1);
            List<ClsInfo> clsInfoList = (List<ClsInfo>)clsInfoLogic.FindAll(ht);
            if (clsInfoList == null) return "";
            //如果年级下没有班级，则不添加进列表中
            if (clsInfoList.Count == 0) continue;

            foreach (ClsInfo clsInfo in clsInfoList)
            {
                string option = "<option value=\"" + clsInfo.RID + "\">" + clsInfo.ClsName + "</option>";
                group += option;
            }

            group += "</optgroup>";

            result += group;
        }

        return result;
    }

    protected static SchoolInfo CurrentSchool
    {
        get
        {
            Perm perm = (Perm)HttpContext.Current.Session["UserInfo"];
            SchoolInfo schInfo = Container<ISchoolInfoLogic>.Instance.FindBySchoolMark(perm.SchoolMark);
            return schInfo;
        }
    }

    public static GlobalTermInfo GloblTermInfo
    {
        get
        {
            IGlobalTermInfoLogic globalTermInfoLogic = Container<IGlobalTermInfoLogic>.Instance;

            List<GlobalTermInfo> globalTermInfoList = (List<GlobalTermInfo>) globalTermInfoLogic.FindAll();
            return globalTermInfoList.Count == 0 ? null : globalTermInfoList[0];
        }
    }

    public static string SchoolOpt
    {
        get
        {
            return ConvertSchoolOptNum(CurrentSchool.SchoolOpt);
        }
    }

    public static string ReportDateType(int reportDateType)
    {
        switch (reportDateType)
        {
            case 1:
                return "日";
            case 2:
                return "周";
            case 3:
                return "月度";
            default:
                return "";
        }
    }

    /// <summary>
    /// 学期
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string ConvertSchoolYear(int schoolyear)
    {
        string str = string.Format("{0} - {1} 学年 ", schoolyear, schoolyear + 1);
        return str;
    }

    /// <summary>
    /// 转换学年和学期
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string ConvertYearAndTerm(int schoolyear, int term)
    {
        string str = string.Format("{0} - {1} 学年 {2}", schoolyear, schoolyear + 1, ConvertTerm(term));
        return str;
    }
    /// <summary>
    /// 转换学期
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public static string ConvertTerm(int term)
    {
        if (term < 1 || term > 2) return "";
        string[] TermStrArr = { "上学期", "下学期" };

        return TermStrArr[term - 1];
    }
    public static readonly EduVersion CurrentVersion = EduVersion.School;
}


#region DES加解密类
/// <summary>
/// DES加解密类
/// </summary>
public class DESEncrypt
{
    #region 私有字段
    private string iv = "1s2o4f5t"; //私钥，初始化向量
    private string key = "b4anseitc";//密钥
    private Encoding encoding = new UnicodeEncoding();
    private DES des;
    #endregion

    /// <summary>
    /// 构造函数
    /// </summary>
    public DESEncrypt()
    {
        des = new DESCryptoServiceProvider();
    }

    #region 属性
    /// <summary>
    /// 设置加密密钥
    /// </summary>
    public string EncryptKey
    {
        get { return this.key; }
        set
        {
            this.key = value;
        }
    }
    /// <summary>
    /// 要加密字符的编码模式
    /// </summary>
    public Encoding EncodingMode
    {
        get { return this.encoding; }
        set { this.encoding = value; }
    }
    #endregion

    #region 方法

    /// <summary>
    /// Encrypt string
    /// </summary>
    /// <param name="strContent">string to be encrypted</param>
    /// <returns>string encrypted</returns>
    public string EncryptString(string strContent)
    {
        string result = "";
        byte[] byKey = null;
        byte[] byIV = null;
        byte[] inputByteArray = null;
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = null;
        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(this.key.Substring(0, 8));
            byIV = System.Text.Encoding.UTF8.GetBytes(this.iv);
            inputByteArray = Encoding.UTF8.GetBytes(strContent);
            //MemoryStream ms = new MemoryStream();
            cs = new CryptoStream(ms, des.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            cs.Close();
            ms.Close();
            result = Convert.ToBase64String(ms.ToArray());
        }
        catch
        {
            if (cs != null)
            {
                cs.Close();
            }
            if (ms != null)
            {
                ms.Close();
            }
            result = null;
        }
        return result;
    }

    /// <summary>
    /// 简单加密字符串
    /// </summary>
    /// <param name="strContent">需要加密的字符串内容</param>
    /// <returns>加密后的数据</returns>
    public string EncryptString_AsicII(string strContent)
    {
        string result = "";
        try
        {
            byte[] bytes = System.Text.UTF8Encoding.ASCII.GetBytes(strContent);
            for (int i = 0; i < bytes.Length; i++)
            {
                // result += bytes[i].ToString().PadLeft(3, '0');
                result += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
            }
        }
        catch
        {
            result = null;
        }
        return result;
    }

    /// <summary>
    /// 简单解密字符串
    /// </summary>
    /// <param name="strContent">需要解密的字符串内容</param>
    /// <returns>解密后的数据</returns>
    public string DecryptString_AsicII(string strContent)
    {
        string result = "";

        try
        {

            string tmpStr = "";
            int cnt = 0;

            for (int i = 0; i < strContent.Length; i++)
            {
                cnt++;
                tmpStr += strContent[i];
                if (cnt % 2 == 0)
                {

                    byte by = Convert.ToByte(tmpStr, 16);
                    byte[] bb = new byte[1];
                    bb[0] = by;
                    result += System.Text.UTF8Encoding.ASCII.GetString(bb);
                    cnt = 0;
                    tmpStr = "";
                }
            }
        }
        catch
        {
            //System.Web.HttpContext.Current.Response.Redirect("~/ErrMessage.aspx?Content=" + EncryptString_AsicII("0000"));
            result = null;
        }
        return result;

    }

    /// <summary>
    /// 加密字符串
    /// </summary>
    /// <param name="str">需要加密的字符串</param>
    /// <returns>加密后2进制数据</returns>
    public byte[] EncryptStringReturnBytes(string str)
    {
        byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
        byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);//得到加密密钥
        byte[] toEncrypt = this.EncodingMode.GetBytes(str);//得到要加密的内容
        byte[] encrypted;
        ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);
        MemoryStream msEncrypt = new MemoryStream();
        CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
        csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
        csEncrypt.FlushFinalBlock();
        encrypted = msEncrypt.ToArray();
        csEncrypt.Close();
        msEncrypt.Close();
        return encrypted;
    }

    /// <summary>
    /// 加密指定的文件,如果成功返回True,否则false
    /// </summary>
    /// <param name="filePath">要加密的文件路径</param>
    /// <param name="outPath">加密后的文件输出路径</param>
    public void EncryptFile(string filePath, string outPath)
    {
        bool isExist = File.Exists(filePath);
        if (isExist)//如果存在
        {
            byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
            byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
            //得到要加密文件的字节流
            FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(fin, this.EncodingMode);
            string dataStr = reader.ReadToEnd();
            byte[] toEncrypt = this.EncodingMode.GetBytes(dataStr);
            fin.Close();

            FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
            ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);
            CryptoStream csEncrypt = new CryptoStream(fout, encryptor, CryptoStreamMode.Write);
            try
            {
                //加密得到的文件字节流
                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
                csEncrypt.FlushFinalBlock();
            }
            catch (Exception err)
            {
                throw new ApplicationException(err.Message);
            }
            finally
            {
                try
                {
                    fout.Close();
                    csEncrypt.Close();
                }
                catch
                {
                    ;
                }
            }
        }
        else
        {
            throw new FileNotFoundException("File not found!");
        }
    }
    /// <summary>
    /// 文件加密函数的重载版本,如果不指定输出路径,
    /// 那么原来的文件将被加密后的文件覆盖
    /// </summary>
    /// <param name="filePath"></param>
    public void EncryptFile(string filePath)
    {
        this.EncryptFile(filePath, filePath);
    }
    /// <summary>
    /// Decrypt string
    /// </summary>
    /// <param name="strContent">string to be decrypted</param>
    /// <returns>string decrypted</returns>
    public string DecryptString(string strContent)
    {
        string result = "";
        byte[] byKey = null;
        byte[] byIV = null;
        byte[] inputByteArray = new Byte[strContent.Length];
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = null;
        try
        {
            byKey = System.Text.Encoding.UTF8.GetBytes(this.key.Substring(0, 8));
            byIV = System.Text.Encoding.UTF8.GetBytes(this.iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(strContent);
            cs = new CryptoStream(ms, des.CreateDecryptor(byKey, byIV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            cs.Close();
            ms.Close();
            System.Text.Encoding encoding = new System.Text.UTF8Encoding();
            result = encoding.GetString(ms.ToArray());
        }
        catch
        {
            if (cs != null)
            {
                cs.Close();
            }
            if (ms != null)
            {
                ms.Close();
            }
            //throw error;
            result = null;
        }
        return result;
    }
    /// <summary>
    /// Decrypt Binary
    /// </summary>
    /// <param name="toDecrypt">Binary  to be decrypted</param>
    /// <returns>string decrypted</returns>
    public string DecryptString(byte[] toDecrypt)
    {
        byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
        byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
        //byte[] toDecrypt=this.EncodingMode.GetBytes(str);
        byte[] deCrypted = new byte[toDecrypt.Length];
        ICryptoTransform deCryptor = des.CreateDecryptor(keyb, ivb);
        MemoryStream msDecrypt = new MemoryStream(toDecrypt);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCryptor, CryptoStreamMode.Read);
        try
        {
            csDecrypt.Read(deCrypted, 0, deCrypted.Length);
        }
        catch (Exception err)
        {
            throw new ApplicationException(err.Message);
        }
        finally
        {
            try
            {
                msDecrypt.Close();
                csDecrypt.Close();
            }
            catch { ;}
        }
        return this.EncodingMode.GetString(deCrypted);

    }

    /// <summary>
    /// 解密指定的文件
    /// </summary>
    /// <param name="filePath">要解密的文件路径</param>
    /// <param name="outPath">解密后的文件输出路径</param>
    public void DecryptFile(string filePath, string outPath)
    {
        bool isExist = File.Exists(filePath);
        if (isExist)//如果存在
        {
            byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
            byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
            FileInfo file = new FileInfo(filePath);
            byte[] deCrypted = new byte[file.Length];
            //得到要解密文件的字节流
            FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //解密文件
            try
            {
                ICryptoTransform decryptor = des.CreateDecryptor(keyb, ivb);
                CryptoStream csDecrypt = new CryptoStream(fin, decryptor, CryptoStreamMode.Read);
                csDecrypt.Read(deCrypted, 0, deCrypted.Length);
            }
            catch (Exception err)
            {
                throw new ApplicationException(err.Message);
            }
            finally
            {
                try
                {
                    fin.Close();
                }
                catch { ;}
            }
            FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
            fout.Write(deCrypted, 0, deCrypted.Length);
            fout.Close();
        }
        else
        {
            throw new FileNotFoundException("File not found!");
        }
    }
    /// <summary>
    /// 解密文件的重载版本,如果没有给出解密后文件的输出路径,
    /// 则解密后的文件将覆盖先前的文件
    /// </summary>
    /// <param name="filePath"></param>
    public void DecryptFile(string filePath)
    {
        this.DecryptFile(filePath, filePath);
    }
    #endregion
}
#endregion